﻿using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using Model;
using System.Web.Configuration;
using System;

namespace BLL
{
    /// <summary>
    /// URL授权类
    /// </summary>
    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 重写OnAuthorization
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            ExtendedDBModelContainer _db = new ExtendedDBModelContainer();

            if (filterContext.HttpContext.User.Identity.Name != null)
            {
                string ControllerName = filterContext.RouteData.Values["controller"].ToString();
                string ActionName = filterContext.RouteData.Values["action"].ToString();

                var item = _db.Sys_ActionsInControllersInRoles.Any(a => a.Sys_Actions.ActionName.Equals(ActionName) && a.Sys_Controllers.ControllerName.Equals(ControllerName) && a.Sys_Roles.Sys_UsersInRoles.Any(b => b.Sys_Users.UserName.Equals(filterContext.HttpContext.User.Identity.Name)));

                if (!item)
                {
                    Error(filterContext);
                }

                //记录用户操作
                if (bool.Parse(WebConfigurationManager.AppSettings["LogToDB"]))
                {
                    var log = new Sys_Users_Logs() { Content = filterContext.HttpContext.Request.Url.AbsolutePath, UserId = _db.Sys_Users.Single(a => a.UserName.Equals(filterContext.HttpContext.User.Identity.Name)).Id };
                    _db.AddToSys_Users_Logs(log);


                    //检查日志保存数量  参数名 LogToDBMax 并执行清理
                    //    <add key="LogToDBMax" value="100" />

                    int logtodbmax = Convert.ToInt32(WebConfigurationManager.AppSettings["LogToDBMax"]);
                    if (_db.Sys_Users_Logs.Count() > logtodbmax)
                    {
                        foreach (var item1 in _db.Sys_Users_Logs.OrderByDescending(a => a.AddDate).Skip(logtodbmax))
                        {
                            _db.Sys_Users_Logs.DeleteObject(item1);
                        }
                    }

                    _db.SaveChanges();
                }
            }
            else
            {
                Error(filterContext);
            }

        }

        private void Error(AuthorizationContext filterContext)
        {
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.Write("没有权限！");
            filterContext.HttpContext.Response.End();
        }
    }
}
